package moe.server;

import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class HttpSession {
	public static final String SESSION_CONTEXT = "HttpSession";

	private Map<String, Object> attributes;
	private String id;
	private long lastAccessedTime;
	private long timeout;

	public HttpSession(String id, long timeout) {
		this.id = id;
		this.timeout = timeout;
		lastAccessedTime = new Date().getTime();
		attributes = new ConcurrentHashMap<String, Object>();
	}

	public Object getAttribute(String name) {
		return attributes.get(name);
	}

	public void setAttribute(String name, Object value) {
		attributes.put(name, value);
	}

	public void removeAttribute(String name) {
		attributes.remove(name);
	}

	public Set<String> getAttributeNames() {
		return attributes.keySet();
	}

	public void activate() {
		lastAccessedTime = new Date().getTime();
	}

	public boolean isStale() {
		return new Date().getTime() > lastAccessedTime + timeout;
	}

	public void invalidate() {
		if (attributes != null) {
			attributes.clear();
			attributes = null;
		}
	}

	public String getId() {
		return id;
	}

	public void clear() {
		attributes.clear();
	}
}
